#include "AlienGenTcpClient.h"

AlienGenTcpClient::AlienGenTcpClient(void )
{

}

AlienGenTcpClient::~AlienGenTcpClient(void )
{

}

int AlienGenTcpClient::connect(const char *host, const char* port)
{
    if(host == NULL)
    {
        return -1;
    }

    SOCKET server_socket=-1;
    struct addrinfo *addressInfo, *rp, hints;

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_INET;    /* Allow IPv4 or IPv6 */
    hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
    hints.ai_flags = 0;
    hints.ai_protocol = 0;          /* Any protocol */

    int err;
    err = getaddrinfo(host, port, &hints, &addressInfo);
    if(err != 0) {
        printf("Unable to retrieve the address on host '%s' with port '%s'\n", host, port);
        return -1;
    }

    qDebug() << "Connection on host " << host << " with port " << port;

    //struct sockaddr_in const *sin;
    //char bufferAddr[INET_ADDRSTRLEN];

    rp = addressInfo;
    while(rp != NULL) {
        server_socket = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
        if(server_socket == -1)
            continue;

        if(::connect(server_socket, rp->ai_addr, rp->ai_addrlen) != -1) {
            /* Retrieve the IP address */
            /*
            sin = (struct sockaddr_in *)rp->ai_addr;
            inet_ntop(rp->ai_family, &sin->sin_addr, bufferAddr, sizeof(bufferAddr));
            query->IPaddress = (char *)calloc(strlen(bufferAddr)+1, sizeof(char));
            strcpy(query->IPaddress, bufferAddr);
            */
            break;
        }
        if(server_socket != -1)
            closesocket(server_socket);

        rp = rp->ai_next;
    }

    freeaddrinfo(addressInfo);
    setSocket(server_socket);

    if(server_socket == -1)
        return -1;

    qDebug() << "Connection on socket" << server_socket;

    return 0;
}

int AlienGenTcpClient::disconnect(void )
{
    SOCKET fd = getSocket();

    /* Closing connection */
    shutdown(fd, 2);
    closesocket(fd);

    setSocket(-1);

    return 0;
}
